<template>
  <div style="padding: 45px;">
    <el-form ref="dataForm" :rules="rules" :model="postForm" label-position="right" label-width="135px">
      <el-form-item label="优惠券标题：" prop="title">
        <el-input v-model="postForm.title" />
      </el-form-item>
      <el-form-item label="门槛金额：" prop="conditionPrice">
        <el-input type="number" placeholder="满多少才可以使用（为0则不限制金额）" v-model="postForm.conditionPrice" />
      </el-form-item>
      <el-form-item label="抵扣价格：" prop="price">
        <el-input type="number" v-model="postForm.price" />
      </el-form-item>
      <el-form-item label="领取起有效天数：" prop="validDays">
        <el-input type="number" v-model="postForm.validDays" />
      </el-form-item>
      <el-form-item label="使用范围：" prop="useRangeType">
        <el-select v-model="postForm.useRangeType " placeholder="使用范围" clearable class="filter-item">
        <el-option v-for="item in typeJson" :key="item.value" :label="item.label" :value="item.value"/>
      </el-select> 
      </el-form-item>
      <el-form-item v-if="postForm.useRangeType == 2">
        <el-card class="box-card" shadow="hover">
          <div slot="header" class="clearfix">
            <span>优惠券适用商品列表</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="addProduct()">添加商品</el-button>
          </div>
          <el-table :data="selectGoodList" fit highlight-current-row row-key="id" style="width: 100%;">
            <el-table-column label="商品编号" prop="identifier" align="center" />
            <el-table-column label="商品名称" prop="name" align="center" />
            <el-table-column label="商品分类" prop="categoryName" align="center" />
            <el-table-column label="供货供应商" prop="splitSupplier" align="center" />
            <el-table-column label="定价" prop="priceText" align="center" />
            <el-table-column label="库存" prop="store" align="center" />
            <el-table-column label="商品类型" prop="isSeckillText" align="center" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
              <template slot-scope="{row}">
                <el-button type="danger" size="mini" @click="handleDeleteGood(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form-item>
      <el-form-item v-if="postForm.useRangeType == 3">
        <el-card class="box-card" shadow="hover">
          <div slot="header" class="clearfix">
            <span>优惠券适用类型列表</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="teaTypedialogVisible = true">添加类型</el-button>
          </div>
          <el-table :data="selectTypeList" fit highlight-current-row row-key="id" style="width: 100%;">
            <el-table-column label="商品分类" prop="label" align="center" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
              <template slot-scope="{row}">
                <el-button type="danger" size="mini" @click="handleDeleteType(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form-item>
      <el-form-item label="时间：" prop="startDate">
        <DatePicker :startDate.sync="postForm.startTime" :endDate.sync="postForm.endTime" clearable />
      </el-form-item>
      <el-form-item label="说明：" prop="remark">
        <el-input type="textarea" v-model="postForm.remark" />
      </el-form-item>
    </el-form>
    
    <el-button style="margin-top: 10px; float: right;" type="primary" @click="submit" >确定</el-button>

    <el-dialog title="商品列表" :close-on-click-modal="false" :visible.sync="dialogVisible" width="1000px">
      <div class="filter-container">
      <el-input v-model="goodsListQuery.identifier$lk" placeholder="商品编号" class="filter-item" clearable/>
      <el-input v-model="goodsListQuery.name$lk" placeholder="商品名称" class="filter-item" clearable/>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
    </div>
      <el-table :data="goodsList" border fit highlight-current-row row-key="id" style="width: 100%;" :max-height="400">
        <el-table-column label="商品编号" prop="identifier" align="center" />
        <el-table-column label="商品名称" prop="name" align="center" />
        <el-table-column label="商品分类" prop="categoryName" align="center" />
        <el-table-column label="供货供应商" prop="splitSupplier" align="center" />
        <el-table-column label="定价" prop="priceText" align="center" />
        <el-table-column label="库存" prop="store" align="center" />
        <el-table-column label="商品类型" prop="isSeckillText" align="center" />
        <el-table-column label="审核状态" align="center">
          <template slot-scope="{row}">
            <el-tag :type="row.status | statusFilter">
              {{ returnValueToLable(row.status,statusJson) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <el-button type="primary" size="mini" @click="handleSelect(row)">
              入选
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination v-show="goodsTotal>0" :total="goodsTotal" :page.sync="goodsListQuery.pageNo" :limit.sync="goodsListQuery.pageSize"
      @pagination="getGoodsList" />

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">
          确定
        </el-button>
      </div>
    </el-dialog>


    <el-dialog title="类型" :close-on-click-modal="false" :visible.sync="teaTypedialogVisible" width="500px">
      <div slot="footer" class="dialog-footer">
        <Cascader v-model="categoryId" ref="categoryId" placeholder="商品分类"
                  :options="categoryData" :props="props" />
        <el-button style="margin-top: 30px;" @click="handleClickType()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { couponPageByQo, couponSave, couponRemove } from '@/api/zcyx'
import { productPageByQo, categoryPageVoByQo } from '@/api/product'
import Cascader from '@/components/Cascader'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination'
import DatePicker from '@/components/DatePicker'
import {mapGetters} from "vuex";

export default {
  name: "ZcyxCouponSave",
  directives: { waves },
  props: {

  },
  components: {
    Cascader,
    Pagination,
    DatePicker
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'danger',
        1: 'success',
        2: '',
        3: 'info'
      }
      return statusMap[status]
    }
  },
  data() {
    const validateDate = (rule, value, callback) => {
      if (!this.postForm.startTime || !this.postForm.endTime) {
        callback(new Error('请选择时间'))
      } else if (new Date(this.postForm.startTime).getTime() < new Date().getTime()) {
        callback(new Error('起始时间必须晚于当前时间'))
      } else if(this.postForm.startTime == new Date().getTime()) {
				callback(new Error('起始时间不能等于当前时间'))
			} else {
        callback()
      }
    }

    return {
      rules: {
        conditionPrice: [{ required: true, message: '请输入', trigger: 'blur' }],
        price: [{ required: true, message: '请输入', trigger: 'blur' }],
        startTime: [{ required: true, message: '请输入', trigger: 'blur' }],
        endTime: [{ required: true, message: '请输入', trigger: 'blur' }],
        validDays: [{ required: true, message: '请输入', trigger: 'blur' }],
        title: [{ required: true, message: '请输入', trigger: 'blur' }],
        remark: [{ required: true, message: '请输入', trigger: 'blur' }],
        useRangeType : [{ required: true, message: '请输入', trigger: 'blur' }],
        startDate: [{validator: validateDate}],
      },
      postForm: {
        conditionPrice: '',
        price: '',
        startTime: '',
        endTime: '',
        validDays: '',
        useRangeType: '',
        useRange: '',
        title: '',
        remark: '',
        platform: 2,
      },
      statusJson: [
        {
          value: '1',
          label: '正常'
        }, {
          value: '0',
          label: '下线'
        }
      ],
      typeJson: [
        {
          value: '1',
          label: '全品类'
        }, 
        {
          value: '2',
          label: '部分商品可用'
        }, 
        {
          value: '3',
          label: '部分类别可用'
        }
      ],
      selectGoodList: [],
      dialogVisible: false,
      goodsList: [],
      goodsTotal: 0,
      goodsListQuery: {
        type: 4,
        isSeckill: 0,
        identifier$lk: '',
        name$lk: '',
        status: "1",
        pageNo: 1,
        pageSize: 20
      },
      teaTypedialogVisible: false,
      categoryId: [],
      categoryData: [],
      props: { value: 'id', label: 'name' },
      selectTypeList: []
    }
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  watch: {},
  methods: {
    getCategory() {
      categoryPageVoByQo().then((res) => {
        this.$set(this, 'categoryData', res || [])
      })
    },
    handleClickType() {
      var label = ""
      var flag = false

      for (let index = 0; index < this.selectTypeList.length; index++) {
        const element = this.selectTypeList[index];
        if (this.categoryId[1] == element.id) {
          flag = true
        }
      }

      if (flag) {
        this.$message.error("已选择");
      } else {
        for (let index = 0; index < this.categoryData.length; index++) {
          const element = this.categoryData[index];
          if (element.id == this.categoryId[0]) {
            label = label + element.name
            
            for (let j = 0; j < element.children.length; j++) {
              const model = element.children[j];
              if (model.id == this.categoryId[1]) {
                label += " / " +  model.name
              }
            }
          }
        }

        var temp = { label: label, id: this.categoryId[1]}
        this.selectTypeList.push(temp)
        this.categoryId = ''
        this.teaTypedialogVisible = false
      }
    },
    handleDeleteType(row) {
      for (let index = 0; index < this.selectTypeList.length; index++) {
        const element = this.selectTypeList[index];
        console.log(888, row, element)
        if (row.id == element.id) {
          this.selectTypeList.splice(index,1);
          return 
        }
      }
    },
    addProduct() {
      this.goodsListQuery.pageNo = 1
      productPageByQo(this.goodsListQuery).then(response => {
        this.goodsList = response.list || []
        this.goodsTotal = response.totalCount
        this.dialogVisible = true
      })
    },
    handleFilter() {
      this.goodsListQuery.pageNo = 1
      this.getGoodsList()
    },
    getGoodsList() {
      productPageByQo(this.goodsListQuery).then(response => {
        this.goodsList = response.list || []
        this.goodsTotal = response.totalCount
      })
      .catch((err) => {
        console.log(err)
        this.listLoading = false
      })
    },
    handleSelect(row) {
      if (this.selectGoodList.length == 0) {
        this.selectGoodList.splice(this.selectGoodList.length, 1, row)
      } else {
        var flag = false
        for (let index = 0; index < this.selectGoodList.length; index++) {
          const element = this.selectGoodList[index];
          if (row.id == element.id) {
            flag = true
          }
        }
        
        if (flag) {
          this.$message.error("已选择");
        } else {
          this.selectGoodList.splice(this.selectGoodList.length, 1, row)
        }
      }
    },
    handleDeleteGood(row) {
      for (let index = 0; index < this.selectGoodList.length; index++) {
        const element = this.selectGoodList[index];
        if (row.id == element.id) {
          this.selectGoodList.splice(index,1);
          return 
        }
      }
    },
    submit() {
      if (this.userInfo.id == 49944) {
        this.postForm.platform = 2
      } else {
        this.postForm.platform = 3
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.postForm.useRangeType == 1) {
            this.postForm.useRange = ''
          }
          if (this.postForm.useRangeType == 2 && this.selectGoodList.length == 0) {
            this.$message.error("优惠券适用商品不能为空");
            return
          }

          if (this.postForm.useRangeType == 3 && this.selectTypeList.length == 0) {
            this.$message.error("优惠券适用类型不能为空");
            return
          }

          if (this.postForm.useRangeType == 2 && this.selectGoodList.length > 0) {
            this.postForm.useRange = ''
            for (let index = 0; index < this.selectGoodList.length; index++) {
              const element = this.selectGoodList[index];
              let temp = ''
              if (index == 0) {
                temp = element.id
              } else {
                temp = "," + element.id
              }

              this.postForm.useRange = this.postForm.useRange + temp
            }
          }

          if (this.postForm.useRangeType == 3 && this.selectTypeList.length > 0) {
            this.postForm.useRange = ''
            for (let index = 0; index < this.selectTypeList.length; index++) {
              const element = this.selectTypeList[index];
              let temp = ''
              if (index == 0) {
                temp = element.id
              } else {
                temp = "," + element.id
              }

              this.postForm.useRange = this.postForm.useRange + temp
            }
          }

          couponSave(this.postForm).then(() => {
            // 调用全局挂载的方法,关闭当前标签页
            this.$store.dispatch("tagsView/delView", this.$route);
              
            this.$router.push({
              path: "/zcyx/zcyxCoupon",
              query: {
                t: Date.now()
              }
            });
          })
        }
      })
    }
  },
  created() {
    this.getCategory()
  },
  mounted() {
    
  },
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>

<style lang='scss' scoped>
  
</style>